package com.huqu.utils;

import java.security.MessageDigest;

import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ApplicationHelper {
	private static ApplicationContext context = new ClassPathXmlApplicationContext(
			"SpringHqContext.xml");
	public static Object findBean(String reposityName) {
		
		return context.getBean(reposityName);
	}
	
	/*redirect page*/
	public static void redirectTo(String url){
		try {
			ApplicationHelper.getResponse().sendRedirect(
					"url");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static String convertToMD5(String arg) {
		String hashed_key = "";

		try {
			byte[] intext = arg.getBytes();
			StringBuffer sb = new StringBuffer();
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			byte[] md5rslt = md5.digest(intext);
			for (int i = 0; i < md5rslt.length; i++) {
				sb.append(String.format("%02x", 0xff & md5rslt[i]));
			}
			hashed_key = sb.toString();
		} catch (Exception e2) {
			System.out.println(e2);
		}
		return hashed_key;
	}
	
	/*
	 * get ExternalContext
	 */
	public static ExternalContext getExContext() {
		return getContext().getExternalContext();
	}
	
	public static HttpServletResponse getResponse() {
		return (HttpServletResponse) getExContext().getResponse();
	}
	
	public static FacesContext getContext() {
		return FacesContext.getCurrentInstance();
	}
	
	public static void showMessageSuccess(String mes) {
		getContext().addMessage(null,new FacesMessage(ApplicationConstant.SEVERITY_INFO,mes, null));
	}
	public static void showMessageErro(String mes) {
		getContext().addMessage(null,new FacesMessage(ApplicationConstant.SEVERITY_ERROR,mes, null));
	}
}
